package com.xtkj.fcsjgromoreads.flutter;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.xtkj.fcsjgromoreads.config.TTAdManagerHolder;
import com.xtkj.fcsjgromoreads.mediation.java.MediationFeedListViewActivity;
import com.xtkj.fcsjgromoreads.mediation.java.MediationMainActivity;
import com.xtkj.fcsjgromoreads.mediation.java.MediationRewardActivity;

import java.util.List;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class FCsjGroMoreAdsPluginDelegate implements MethodChannel.MethodCallHandler, EventChannel.StreamHandler {
    private static final String TAG = "FCsjGroMoreAdsPlugin";
    private MethodChannel.Result mMethodChannelResult;
    private EventChannel.EventSink mEventChannelEventSink;
    private FlutterPlugin.FlutterPluginBinding mPluginBinding;
    private Activity mActivity;

    public FCsjGroMoreAdsPluginDelegate(FlutterPlugin.FlutterPluginBinding pluginBinding, Activity activity) {
        this.mPluginBinding = pluginBinding;
        this.mActivity = activity;
    }

    @Override
    public void onListen(Object arguments, EventChannel.EventSink events) {
        this.mEventChannelEventSink = events;
    }

    @Override
    public void onCancel(Object arguments) {
        this.mEventChannelEventSink = null;
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        String method = call.method;
        Object arguments = call.arguments;
        Log.d(TAG,"method="+method+",arguments="+arguments);
        switch (method){
            case "requestIosIDFA":
                break;
            case "requestAndroidPermissionIfNecessary":
                requestAndroidPermissionIfNecessary(call,result);
                break;
            case "initCsjAd":
                initCsjAd(call,result);
                break;
            case "showFeedListAd":
                showFeedListAd(call,result);
                break;
            case "showRewardAd":
                showRewardAd(call,result);
                break;
            case "showFullInteractionAd":
                break;
        }
    }

    private void showRewardAd(MethodCall call, MethodChannel.Result result) {
        String mMediaId = call.argument("mMediaId");
        Intent intent = new Intent(mActivity, MediationRewardActivity.class);
        intent.putExtra("mMediaId",mMediaId);
        mActivity.startActivity(intent);
    }

    private void showFeedListAd(MethodCall call, MethodChannel.Result result) {
        String mMediaId = call.argument("mMediaId");
        double width = call.argument("width");
        double height = call.argument("height");
        int count = call.argument("count");
        Intent intent = new Intent(mActivity, MediationFeedListViewActivity.class);
        intent.putExtra("mMediaId",mMediaId);
        intent.putExtra("width",width);
        intent.putExtra("height",height);
        intent.putExtra("count",count);
        mActivity.startActivity(intent);
        result.success(true);
    }

    private void requestAndroidPermissionIfNecessary(MethodCall call, MethodChannel.Result result) {
        try {
            TTAdManagerHolder.get().requestPermissionIfNecessary(mActivity.getApplicationContext());
            result.success(true);
        }catch (Exception e){
            result.success(false);
        }
    }

    private void initCsjAd(MethodCall call, MethodChannel.Result result) {
        String appId = call.argument("appId");
        boolean allowShowNotify = call.argument("allowShowNotify");
        List<Integer> directDownloadNetworkTypeArr = call.argument("directDownloadNetworkType");
        int[] directDownloadNetworkTypes = new int[directDownloadNetworkTypeArr.size()];
        for(int i=0;i<directDownloadNetworkTypeArr.size();i++){
            directDownloadNetworkTypes[i]=directDownloadNetworkTypeArr.get(i);
        }
        TTAdConfig config = new TTAdConfig.Builder()
                /**
                 * 注：需要替换成在媒体平台申请的appID ，切勿直接复制
                 */
                .appId(appId)
//                .appName("APP测试媒体")
                .allowShowNotify(allowShowNotify)
                /**
                 * 上线前需要关闭debug开关，否则会影响性能
                 */
                .debug(true)
                .supportMultiProcess(true)
                .directDownloadNetworkType(directDownloadNetworkTypes)
                /**
                 * 使用聚合功能此开关必须设置为true，默认为false，不会初始化聚合模板，聚合功能会吟唱
                 */
                .useMediation(true)
//                .customController(getTTCustomController()) //如果您需要设置隐私策略请参考该api
//                .setMediationConfig(new MediationConfig.Builder() //可设置聚合特有参数详细设置请参考该api
//                        .setMediationConfigUserInfoForSegment(getUserInfoForSegment())//如果您需要配置流量分组信息请参考该api
//                        .build())
                .build();
        TTAdSdk.init(mActivity.getApplicationContext(), config);
        TTAdSdk.start(new TTAdSdk.Callback() {
            @Override
            public void success() {
                Log.i(TAG,"success: " + TTAdSdk.isInitSuccess());
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        result.success(true);
                    }
                });
            }

            @Override
            public void fail(int code, String msg) {
                Log.i(TAG, "fail:  code = " + code + " msg = " + msg);
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        result.success(false);
                    }
                });
            }
        });
    }
}
